<template>
  <div class="word-learning-page">
    <!-- 顶部导航栏 -->
    <header class="top-nav">
      <div>
        <!-- 回退按钮（靠左） -->
        <el-button
          icon="fa-solid fa-arrow-left"
          class="nav-btn back-btn"
          size="medium"
          @click="$emit('change-view', 'index')"
        />
        <span>挑选生词</span>
      </div>
      <div class="top-nav__right">
        <!-- 倍速播放控制（点击展开/收起） -->
        <div ref="speedControlRef" class="speed-control">
          <!-- 速度显示/触发按钮 -->
          <el-button
            class="speed-control__trigger"
            size="medium"
            :icon="showSpeedSlider ? 'fa-solid fa-chevron-up' : 'fa-solid fa-tachometer-alt'"
            @click="toggleSpeedSlider"
          >
            {{ playbackSpeed.toFixed(1) }}x
          </el-button>

          <!-- 展开后的滑块区域 -->
          <div
            v-if="showSpeedSlider"
            class="speed-control__slider-wrap"
          >
            <!-- 滑块 -->
            <el-slider
              v-model="playbackSpeed"
              :min="0.5"
              :max="2"
              :step="0.1"
              :format-tooltip="formatSpeed"
              class="speed-slider"
            />

            <!-- 复位按钮 -->
            <el-button
              class="speed-control__reset-btn"
              size="mini"
              @click="resetSpeed"
            >
              复位 1.0x
            </el-button>
          </div>
        </div>

        <!-- 发音切换 (美式/英式) -->
        <el-button
          class="nav-btn accent-btn"
          size="medium"
          :class="{ 'is-active': true }"
          @click="toggleAccent"
        >
          <span>{{ isAmerican ? '美音' : '英音' }}</span>
        </el-button>

        <!-- 音标显示/隐藏 -->
        <el-button
          class="nav-btn phonetic-btn"
          size="medium"
          @click="togglePhonetic"
        >
          <span :class="['phonetic-label', { 'is-off': !showPhonetic }]">音标</span>
        </el-button>
      </div>
    </header>

    <!-- 加载动画 -->
    <div v-if="pageLoading && displayedWords.length===0" class="page-loading-container">
      <div class="page-loading-content">
        <i class="el-icon-loading"></i>
        <p>加载单词数据中...</p>
      </div>
    </div>

    <!-- 中间滚动列表区域 -->
    <main v-else class="word-list-container">
      <div
        class="word-list"
        @scroll="handleScroll"
      >
        <div
          v-for="(word, index) in displayedWords"
          :key="index"
          class="word-item"
          :class="{
            'word-known': word.status === 'known',
            'word-unknown': word.status === 'unknown'
          }"
          @click="playPronunciation(word,index)"
        >
          <!-- 单词和音标 -->
          <div class="word-info">
            <div class="word-main">
              <h3 class="word-text">
                <span
                  @click.stop="playEn(word.fullSpell ? word.fullSpell : word.wordFullSpell ? word.wordFullSpell : 'I don\'t know')"
                >{{ word.fullSpell ? word.fullSpell : word.wordFullSpell ? word.wordFullSpell : '🤔' }}</span>
              </h3>
              <p v-if="showPhonetic" class="word-phonetic">
                <span>{{ isAmerican ? word.phoneticAm : word.phoneticBr }}</span>
              </p>

              <!-- 单词意思 -->
              <div v-if="word.clickCount % 3 === 2" class="word-meaning">
                <span @click.stop="playZh(word.wordMeaning.replace(/[A-Za-z]/g, ''))">{{ word.wordMeaning }}</span>
              </div>
            </div>

            <!-- 快速标记按钮 -->
            <div class="quick-actions">
              <el-button
                icon="fa-solid fa-check"
                class="quick-btn"
                :class="{ 'known-btn': word.status === 'known' }"
                @click.stop="toggleKnown(index)"
              />
              <el-button
                icon="fa-solid fa-times"
                class="quick-btn"
                :class="{ 'unknown-btn': word.status === 'unknown' }"
                @click.stop="toggleUnknown(index)"
              />
            </div>
          </div>
        </div>

        <!-- 加载提示 -->
        <div v-if="isLoading" class="loading-indicator">
          <i class="el-icon-loading"></i>
          <p>加载更多单词...</p>
        </div>

        <!-- 没有更多数据 -->
        <div v-if="!hasMoreData && !isLoading" class="no-more">
          <p>已经没有更多单词了</p>
        </div>
      </div>
    </main>

    <!-- 底部统计栏 -->
    <footer class="bottom-nav">
      <div>
        <span>已选 {{ unknownCount }} 个生词</span>
      </div>
      <div class="word-actions">
        <!-- 能认识 -->
        <div class="can-learn">
          <span>😀</span>
          <span class="badge">{{ knownCount }}</span>
        </div>
        <!-- 不认识 -->
        <div class="not-learn">
          <span>😔</span>
          <span class="badge">{{ unknownCount }}</span>
        </div>
      </div>
      <div>
        <el-button
          class="nav-btn start-learn"
          size="medium"
          @click="disorder"
        >
          <i class="fa-solid fa-teeth-open"></i>
          乱序
        </el-button>
        <el-button
          class="nav-btn start-learn"
          size="medium"
          :loading="startLearnLoading"
          :disabled="startLearnLoading"
          @click="handleStartLearn"
        >
          <i class="fa-solid fa-play"/>
          {{ startLearnLoading ? '提交中...' : '开始学新' }}
        </el-button>
      </div>
    </footer>

    <FireworkTransition ref="firework"/>
  </div>
</template>

<script>
import { startStudyNewWord, unlearnedVocabulary } from '@/api/wordSystemCourse'
import FireworkTransition from '@/views/course/component/courseTeach/wordLearning/FireworkTransition.vue'
import AudioCacheUtil from '@/utils/AudioCacheUtil'

export default {
  name: 'WordLearning',
  components: { FireworkTransition },
  data() {
    return {
      // 状态控制
      showPageWhat: 'review',
      isAmerican: true, // 美式发音
      showPhonetic: true, // 显示音标
      playbackSpeed: 1.0, // 播放速度
      currentPage: 1, // 当前页码
      pageSize: 30, // 每页数量
      isLoading: false, // 是否加载中
      hasMoreData: true, // 是否有更多数据
      // 新增：控制倍速滑块展开/收起
      showSpeedSlider: false,

      // 新增加载状态
      pageLoading: false, // 页面加载状态
      startLearnLoading: false, // 开始学习按钮加载状态
      isSubmitting: false, // 防抖标志

      // 单词数据
      allWords: [], // 所有单词
      displayedWords: [], // 显示的单词

      bundleId: '',

      nowClickWord: {}
    }
  },
  computed: {
    knownCount() {
      return this.displayedWords.filter(w => w.status === 'known').length
    },
    unknownCount() {
      return this.displayedWords.filter(w => w.status === 'unknown').length
    }
  },
  watch: {
    // 判断当前点击的按钮是否为连续点击 如果不是 需要将上一次的按钮点击次数清零
    'nowClickWord'(newValue, oldValue) {
      if (newValue.id !== oldValue.id) {
        oldValue.clickCount = 0
      }
    }
  },
  // ✅ 新增：组件销毁时清除监听
  beforeDestroy() {
    document.removeEventListener('click', this.handleClickOutside)
  },
  created() {
    // 初始化加载第一页数据
    this.loadWords()
  },
  methods: {
    async handleStartLearn() {
      // 防抖处理
      if (this.isSubmitting) {
        return
      }

      this.isSubmitting = true
      this.startLearnLoading = true

      try {
        const idArr = []
        this.displayedWords.forEach(word => {
          if (word.status === 'unknown') {
            idArr.push('-' + word.id)
          } else if (word.status === 'known') {
            idArr.push(word.id)
          }
        })

        if (idArr.length === 0) {
          this.$notify.warning({ message: '请选择生词' })
          return
        }

        this.bundleId = await startStudyNewWord(idArr)
        if (this.bundleId < 0) {
          this.$refs.firework.setDuration(2000).startConfetti('太棒了👍 所选单词无需学习！')
          setTimeout(() => {
            this.init()
            this.loadWords()
          }, 500)
          return
        }
        this.$emit('startToLearn', this.bundleId)
      } catch (error) {
        console.error('开始学习失败:', error)
      } finally {
        this.isSubmitting = false
        this.startLearnLoading = false
      }
    },

    // 乱序 对单词顺序进行打乱
    disorder() {
      const arr = [...this.displayedWords]
      for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1))
        ;[arr[i], arr[j]] = [arr[j], arr[i]]
      }
      this.displayedWords = arr
    },

    init() {
      this.allWords = []
      this.displayedWords = []
      this.currentPage = 1
    },

    // 格式化速度显示
    formatSpeed(value) {
      return `${value}x`
    },

    // 切换发音（美式/英式）
    toggleAccent() {
      this.isAmerican = !this.isAmerican
    },

    // 切换音标显示/隐藏
    togglePhonetic() {
      this.showPhonetic = !this.showPhonetic
    },

    playZh(text) {
      AudioCacheUtil.play(text, 'zh', this.playbackSpeed)
    },

    playEn(text) {
      AudioCacheUtil.play(text, this.isAmerican ? 'en' : 'uk', this.playbackSpeed)
    },

    // 播放单词发音
    playPronunciation(word) {
      AudioCacheUtil.play(word.fullSpell ? word.fullSpell : word.wordFullSpell, this.isAmerican ? 'en' : 'uk', this.playbackSpeed)
      word.clickCount++
      this.nowClickWord = word
    },

    // 处理滚动加载
    handleScroll(e) {
      const container = e.target
      // 当滚动到底部附近时加载更多
      if (container.scrollHeight - container.scrollTop - container.clientHeight < 300 &&
        !this.isLoading &&
        this.hasMoreData) {
        this.loadMoreWords()
      }
    },

    // 加载单词数据
    async loadWords() {
      this.pageLoading = true
      this.isLoading = true

      try {
        const res = await unlearnedVocabulary({
          page: {
            pageNum: this.currentPage,
            pageSize: this.pageSize
          },
          param: {
            cid: this.$route.query.q1
          }
        })

        res.records.forEach(word => {
          word.status = ''
          word.clickCount = 0
        })

        this.allWords = [...this.allWords, ...res.records]
        res.records.forEach(word => {
          this.displayedWords.push(word)
        })

        if (res.records.length < this.pageSize) {
          this.hasMoreData = false
        }
      } catch (error) {
        console.error('加载单词数据失败:', error)
      } finally {
        this.pageLoading = false
        this.isLoading = false
      }
    },

    // 加载更多单词
    loadMoreWords() {
      this.currentPage++
      this.loadWords()
    },

    // ✅ 修改 toggleSpeedSlider 方法
    toggleSpeedSlider() {
      this.showSpeedSlider = !this.showSpeedSlider

      // ✅ 如果展开，则绑定 document 点击监听；否则解绑
      if (this.showSpeedSlider) {
        document.addEventListener('click', this.handleClickOutside)
      } else {
        document.removeEventListener('click', this.handleClickOutside)
      }
    },

    // ✅ 新增：点击外部关闭滑块
    handleClickOutside(e) {
      const controlEl = this.$refs.speedControlRef
      if (controlEl && !controlEl.contains(e.target)) {
        this.showSpeedSlider = false
        document.removeEventListener('click', this.handleClickOutside)
      }
    },

    // 新增：复位播放速度到1.0x
    resetSpeed() {
      this.playbackSpeed = 1.0
      // 复位后可选择自动收起滑块
      this.showSpeedSlider = false
      document.removeEventListener('click', this.handleClickOutside) // ✅ 防止监听残留
    },

    // 切换"认识"按钮
    toggleKnown(index) {
      const word = this.displayedWords[index]
      if (word.status === 'known') {
        word.status = null // 再点一次取消
      } else {
        word.status = 'known' // 互斥，覆盖为 known
      }
    },

    // 切换"不认识"按钮
    toggleUnknown(index) {
/*       if (this.unknownCount >= 30) {
        this.$notify.warning({ message: '已选择30个生词，学完再学下一批吧！' })
        return
      } */
      const word = this.displayedWords[index]
      if (word.status === 'unknown') {
        word.status = null
      } else {
        word.status = 'unknown'
      }
    }
  }
}
</script>

<style scoped>
* {
  user-select: none;
}

.word-learning-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background-color: #f5f7fa;
}

/* 页面加载动画样式 */
.page-loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.page-loading-content {
  text-align: center;
  color: #909399;
}

.page-loading-content i {
  font-size: 40px;
  margin-bottom: 16px;
  color: #409EFF;
  animation: rotating 2s linear infinite;
}

.page-loading-content p {
  font-size: 16px;
}

/* 中间单词列表区域 */
.word-list-container {
  flex-grow: 1;
  overflow: hidden;
  padding: 5px;
}

.word-list {
  height: 100%;
  overflow-y: auto;
}

.word-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.word-main {
  flex-grow: 1;
}

.word-text {
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 4px 0;
  color: #2c3e50;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;

  position: relative;
  user-select: none;

  span {
    cursor: pointer;
  }
}

.word-phonetic {
  font-size: 18px;
  color: #999;
  margin: 10px 0 0 0;
  font-style: italic;
}

.word-meaning {
  color: #555;
  margin-top: 20px;

  span {
    cursor: pointer;
  }
}

.quick-actions {
  display: flex;
  gap: 5px;
}

.quick-btn {
  width: 36px;
  height: 36px;
  padding: 0;
  margin: 0;
  border-radius: 50%;
  background-color: transparent; /* 默认透明 */
  border: 1px solid #ccc; /* 给个轻微边框 */
  color: #555;
  transition: all 0.2s ease;
}

.quick-btn:hover {
  background-color: #f5f5f5;
}

.known-btn {
  background-color: #e6f7ed !important;
  color: #239744 !important;
  border-color: #239744 !important;
}

.unknown-btn {
  background-color: #fde2e2 !important;
  color: #e53e3e !important;
  border-color: #e53e3e !important;
}

/* 加载状态 */
.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24px;
  color: #666;
}

.loading-indicator i {
  font-size: 24px;
  margin-bottom: 8px;
  color: #409EFF;
  animation: rotating 2s linear infinite;
}

.no-more {
  text-align: center;
  padding: 24px;
  color: #999;
}

/* 底部菜单栏 */
.bottom-nav {
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  align-items: center;
  height: 56px;
  background-color: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

/* 滚动条美化 */
.word-list::-webkit-scrollbar {
  width: 0;
}

/* 顶部导航栏整体样式 */
.top-nav {
  display: flex;
  align-items: center;
  justify-content: space-between; /* 左右布局分离 */
  padding: 0 16px;
  height: 50px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
  position: relative; /* 为滑块下拉层提供定位基准 */
}

/* 右侧功能区容器（统一靠右） */
.top-nav__right {
  display: flex;
  align-items: center;
  gap: 12px; /* 按钮间距统一 */
}

/* 统一按钮基础样式 */
.nav-btn {
  padding: 8px 12px;
  border-radius: 20px; /* 圆角更柔和 */
  background-color: transparent;
  color: #333;
  transition: all 0.2s ease;
  border: 1px solid transparent;
  font-size: 14px;
}

.nav-btn:hover {
  background-color: #f5f7fa;
  border-color: #e0e0e0;
}

.start-learn {
  border: 1px solid #e0e0e0;
}

.start-learn:hover {
  color: #0084ff;
}

/* 发音按钮激活态（增强视觉反馈） */
.accent-btn.is-active {
  background-color: #e6f4ea;
  color: #239744;
  border-color: #d1e7dd;
}

/* 倍速控制容器 */
.speed-control {
  position: relative; /* 滑块下拉层相对定位 */
  display: flex;
  align-items: center;
}

/* 倍速触发按钮 */
.speed-control__trigger {
  padding: 8px 12px;
  border-radius: 20px;
  background-color: #f5f7fa;
  color: #333;
  border: 1px solid transparent;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 6px; /* 图标与文字间距 */
}

.speed-control__trigger:hover {
  background-color: #e9ecef;
  border-color: #dee2e6;
}

/* 倍速滑块容器（下拉层） */
.speed-control__slider-wrap {
  position: absolute;
  top: 60px; /* 位于触发按钮下方 */
  left: -50px;
  width: 220px;
  padding: 12px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 8px;
  z-index: 20; /* 确保在其他元素上方 */
  /* 淡入动画 */
  animation: fadeIn 0.2s ease forwards;
}

/* 滑块样式 */
.speed-slider {
  flex-grow: 1;
  margin: 0;
}

/* 复位按钮样式 */
.speed-control__reset-btn {
  padding: 4px 8px;
  border-radius: 4px;
  background-color: #f0f9ff;
  color: #1890ff;
  border-color: #91d5ff;
}

.speed-control__reset-btn:hover {
  background-color: #e6f7ff;
  border-color: #69c0ff;
}

/* 音标按钮样式（保持原有逻辑，优化细节） */
.phonetic-label {
  position: relative;
  display: inline-block;
  padding: 0 2px;
  color: #333;
  transition: color 0.2s ease;
}

.phonetic-label::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  height: 2px;
  top: 50%;
  transform: translateY(-50%) scaleX(0);
  transform-origin: left center;
  background: #ff4d4f; /* 横线用醒目红色 */
  transition: transform 0.25s cubic-bezier(.2, .9, .2, 1);
  pointer-events: none;
}

.phonetic-label.is-off {
  color: #999;
}

.phonetic-label.is-off::after {
  transform: translateY(-50%) scaleX(1);
}

/* 淡入动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 旋转动画 */
@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.phonetic-btn {
  margin: 0;
}

/* 默认卡片样式 */
.word-item {
  background-color: #fff;
  border-radius: 12px;
  padding: 10px;
  margin-top: 16px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

/* 认识状态：淡绿色背景 */
.word-item.word-known {
  background-color: #e6f7ed;
  border: 1px solid #239744;
}

/* 不认识状态：淡红色背景 */
.word-item.word-unknown {
  background-color: #fde2e2;
  border: 1px solid #e53e3e;
}

/* 按钮默认透明，选中时保留高亮 */
.quick-btn {
  width: 36px;
  height: 36px;
  padding: 0;
  margin: 0;
  border-radius: 50%;
  background-color: transparent;
  border: 1px solid #ccc;
  color: #555;
  transition: all 0.2s ease;
}

.quick-btn:hover {
  background-color: #f5f5f5;
}

.known-btn {
  background-color: #239744 !important;
  color: #fff !important;
  border-color: #239744 !important;
}

.unknown-btn {
  background-color: #e53e3e !important;
  color: #fff !important;
  border-color: #e53e3e !important;
}

.word-actions {
  display: flex;
  gap: 40px;
  margin-top: 12px;
  position: relative;

  div {
    font-size: 40px;
  }

  .not-learn {
    color: rgb(229, 62, 62);
  }

  .can-learn {
    color: rgb(35, 151, 68);
  }
}

.word-actions > div {
  position: relative;
  font-size: 40px;
}

/* 徽标样式 */
.badge {
  position: absolute;
  top: -6px;
  right: -10px;
  min-width: 20px;
  height: 20px;
  padding: 0 6px;
  border-radius: 10px;
  background-color: #ff4d4f;
  color: #fff;
  font-size: 12px;
  font-weight: bold;
  line-height: 20px;
  text-align: center;
}

/* 认识用绿色徽标 */
.can-learn .badge {
  background-color: #52c41a;
}

/* 不认识用红色徽标 */
.not-learn .badge {
  background-color: #ff4d4f;
}

.word-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  background-color: #00b578;
}

.word-item:hover span,
.word-item:hover h3 {
  color: white;
}
</style>
